package com.quwan.manager.service.impl;

import com.quwan.common.enums.JobTypeEnum;
import com.quwan.entity.JobLock;
import com.quwan.manager.controller.dto.JobLockDTO;
import com.quwan.mapper.JobLockMapper;
import com.quwan.manager.service.IJobLockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * <p>
 * 定时任务锁表 服务实现类
 * </p>
 *
 * @author quwan
 * @since 2021-11-24
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class JobLockServiceImpl extends ServiceImpl<JobLockMapper, JobLock> implements IJobLockService {

    private final JobLockMapper jobLockMapper;

    @Override
    public JobLockDTO getVersion(Byte type) {
        JobLockDTO jobLockDTO = jobLockMapper.selectTaskLock(type);
        if (jobLockDTO == null) {
            jobLockMapper.createTaskLock(type, new Date());
            jobLockDTO = new JobLockDTO();
            jobLockDTO.setType(type);
            jobLockDTO.setVersion((long) 1);
        }
        log.info(JobTypeEnum.getMsgByCode(type) + "获取锁版本号：" + jobLockDTO.getVersion());
        return jobLockDTO;
    }

    @Override
    public int updateVersion(Byte type, Long version) {
        log.info(JobTypeEnum.getMsgByCode(type) + "准备修改版本号：" + version);
        int i = 0;
        if (version.equals(new Long(1))) {
            // 该任务是第一次创建，不去判断时间问题     数据库有type和version的唯一索引，不用担心多台服务器创建多条相同数据
            i = jobLockMapper.updateLockVersion(version, type, null);
        } else {
            i = jobLockMapper.updateLockVersion(version, type, Date.from(LocalDateTime.now().minusMinutes(10).atZone(ZoneId.systemDefault()).toInstant()));
        }
        if (i == 1) {
            log.info(JobTypeEnum.getMsgByCode(type) + "修改版本号成功");
        } else {
            log.info(JobTypeEnum.getMsgByCode(type) + "修改版本号失败");
        }
        return i;
    }
}
